package net.tmaize.service;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DownloadImage extends HttpServlet {

	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {

		response.setContentType("image/jpeg");
		// 设置图片缓存，减轻服务器压力
		// Last-Modified:页面的最后生成时间
		response.setDateHeader("Last-Modified", new Date().getTime());
		// Expires:过时期限值 2小时
		response.setDateHeader("Expires", new Date().getTime() + 2 * 60 * 60 * 1000);
		// Cache-Control来控制页面的缓存与否,public:浏览器和缓存服务器都可以缓存页面信息；
		response.setHeader("Cache-Control", "public");
		// Pragma:设置页面是否缓存，为Pragma则缓存，no-cache则不缓存
		response.setHeader("Pragma", "Pragma");
		try {
			String imageUrl = request.getParameter("url");
			URL url = new URL(imageUrl);
			HttpURLConnection con = (HttpURLConnection) url.openConnection();
			InputStream is = con.getInputStream();
			BufferedImage image = ImageIO.read(is);
			is.close();
			con.disconnect();
			ImageIO.write(image, "jpeg", response.getOutputStream());
		} catch (IOException e) {
			// 页面下载图片失败，长时间无响应
			response.sendRedirect(request.getContextPath() + "/error.html");
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
